﻿using Ldt.DataEngine.RuleAssemble;
using LdtJudge.DataEngine.Common.StringAssemble;
using LdtJudge.DataEngine.Model.Personnel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace LdtDataEngin.ModuleDetail.PersonnelAnalysis
{
    /// <summary>
    /// 通用分析方法
    /// </summary>
    public class CommonAnalysisModel
    {
        public string CaseType { get; set; }
        /// <summary>
        /// 通用分析方法
        /// </summary>
        /// <returns></returns>
        public string Satrct(IList<ElementSpokeName> ListName, string newOriginalText, string flag)
        {
            string regPattern = string.Empty;
            var query = from item in ListName
                        where !string.IsNullOrWhiteSpace(item.ES_SuitDegreeName) && (!string.IsNullOrWhiteSpace(item.ES_FullName) || !string.IsNullOrWhiteSpace(item.ES_ShortName))
                        group item by item.ES_SuitDegreeName into g
                        select new { Group = g.Key, Member = g };
            string Renyuan = RuleParseClass.GetRegString("CourtSpokeParseA23");
            foreach (var item in query)
            {
                string allFullName = string.Join("|", item.Member.Select(x => x.ES_FullName).ToList<string>());
                string allShortName = string.Join("|", item.Member.Select(x => x.ES_FullName).ToList<string>());
                allFullName += (allShortName == string.Empty) ? "" : "|" + allShortName;
                regPattern += (regPattern == "") ? "" : "|";
                string suitname = item.Group;
                if (suitname == "犯罪嫌疑人")
                {
                    suitname = "被告";
                }

                regPattern += Renyuan.Replace("@{Name}", suitname).Replace("@{Name_a}", allFullName.Replace("*", "\\*"));
            }
            //替换值文本集合0
            Dictionary<string, string> replaceDict = new Dictionary<string, string>();

            MatchCollection matchArr = Regex.Matches(newOriginalText, regPattern);
            if (!string.IsNullOrEmpty(regPattern))
            {
                List<Tuple<int, int, int>> replacedList = new List<Tuple<int, int, int>>();//记录已替换的位置
                for (int z = matchArr.Count - 1; z >= 0; z--)
                {
                    Match match = matchArr[z];
                    string extractValue = match.Value;
                    string extrname = extractValue.Replace("原告", "").Replace("、", "").Replace(",", "").Trim();
                    if (extractValue == "原告" || extractValue.IndexOf("原告") == -1 || extrname == null || LdFormat.DecodeNumberCn(extrname) == 1)
                    {
                        //处理匹配到 比如三被告共同的情况 此情况下被告不做替换 第一、二被告----第一被告、第二被告
                        try
                        {
                            if (newOriginalText.Length >= match.Index && match.Index - 2 > -1)
                            {
                                string last = newOriginalText.Substring(match.Index - 2, 2);//取名称前2个字
                                //if (RegexParseClass.IsMatch("CourtSpokeParseA6", last))
                                //{
                                //    continue;
                                //}
                            }
                        }
                        catch (Exception err)
                        {

                        }
                        string replaceValue = string.Empty;
                        List<string> queryperson = new List<string>();
                        if (replaceDict.ContainsKey(extractValue))
                        {
                            replaceValue = replaceDict[extractValue];
                        }
                        else
                        {
                            PersonnelConversion baseAnalysis = new PersonnelConversion() { spokenamelist = ListName };
                            IList<ElementSpokeName> matchList2 = baseAnalysis.GetMatchSpokeManByRoleName(ListName, extractValue.Replace("、", ""), CaseType);

                            if (string.IsNullOrEmpty(flag))
                            {
                                queryperson = (from person in matchList2
                                               where (person.ES_SuitDegreeName != "" || person.ES_FullName != "")
                                               select person.ES_SuitDegreeName + person.ES_FullName).Distinct().ToList();
                            }
                            else
                            {
                                queryperson = (from person in matchList2
                                               where (person.ES_SuitDegreeName != "" || person.ES_FullName != "")
                                               select person.ES_FullName).Distinct().ToList();
                            }
                            replaceValue = String.Join("、", queryperson);
                            var next = matchArr.Cast<Match>().SingleOrDefault(a => a.Index == match.Index + match.Length);
                            //兼容人员替换后无顿号的情况
                            if (extractValue.EndsWith("、") && next != null)
                            {
                                replaceDict.Add(extractValue, replaceValue + "、");
                            }
                            else if (extractValue.EndsWith("、") && next == null)
                            {
                                replaceDict.Add(extractValue, replaceValue);
                            }
                            else
                            {
                                replaceDict.Add(extractValue, replaceValue);
                            }
                        }
                        try
                        {
                            string test = newOriginalText.Substring(match.Index + match.Length);
                            bool isreplace = true;
                            foreach (var sp in ListName)
                            {
                                if (sp != null && sp.ES_ShortName != null)
                                {
                                    if ((replaceValue.IndexOf(sp.ES_ShortName) > 0 && test.StartsWith(sp.ES_ShortName)) || replaceValue == "")
                                    {
                                        isreplace = false;
                                        break;
                                    }
                                }
                            }
                            if (isreplace)
                            {
                                newOriginalText = newOriginalText.Remove(match.Index, match.Length);
                                newOriginalText = newOriginalText.Insert(match.Index, replaceValue);
                            }
                        }
                        catch (Exception err)
                        {

                        }
                        var it = replacedList.LastOrDefault();
                        //判断上次替换之前名称是否连接
                        if (it != null)
                        {
                            if (it.Item1 == match.Index + match.Length)
                            {
                                if (!string.IsNullOrEmpty(replaceValue))
                                {
                                    if (newOriginalText.ToArray()[match.Index + replaceValue.Length - 1] != '、')
                                    {
                                        newOriginalText = newOriginalText.Insert(match.Index + replaceValue.Length, "、");
                                    }
                                }

                            }
                        }
                        if (!replaceValue.EndsWith("、"))
                        {
                            //记录上次替换的位置 防止原被告这种直接连接的替换后无顿号
                            Tuple<int, int, int> tp = new Tuple<int, int, int>(match.Index, match.Length, replaceValue.Length);
                            replacedList.Add(tp);
                        }
                    }

                }
            }

            return newOriginalText;
        }
    }
}
